package com.yj.suncity.user;

import java.util.List;

import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.activity.shouye.ProductDateilsActivity;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.bean.GoodsBean;
import com.yj.suncity.bean.GoodsListBean;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.PullToRefreshView;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.DialogUtils.ReshActivity;
import com.yj.suncity.utis.PullToRefreshView.OnFooterRefreshListener;
import com.yj.suncity.utis.PullToRefreshView.OnHeaderRefreshListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class UserDigouListActivity extends Activity implements
		OnHeaderRefreshListener, OnFooterRefreshListener {

	private Context context;
	private ListView mListView;
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private String userId;
	private String titleName;

	private boolean mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
	private boolean mRefreshFlag = false;// 判断是否刷新
	private PullToRefreshView mPullToRefreshView = null;
	private int pageNum = 1;
	private DigouAdapter adapter;
	private List<GoodsBean> detailInfos;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_digou_shop);
		context = this;
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				.displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		userId = getIntent().getStringExtra("userid");
		titleName = getIntent().getStringExtra("titlename");
		findView();
		initData(1);
	}

	private void findView() {
		((TextView) findViewById(R.id.txt_title_name)).setText(titleName);

		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		mListView = (ListView) findViewById(R.id.list_view_digou);
		TextView emptyView = (TextView) findViewById(R.id.txt_empty);
		mListView.setEmptyView(emptyView);

	}

	private void initData(int index) {
		String path = URLCon.兑换抵购
				+ "?action=getgoodsrecord&pagesize=20&pageindex=" + index
				+ "&releasetype=2&userid=" + userId + "&state=0";
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null,
				mPullToRefreshView, mRefreshFlag, null, true, "正在加载......",
				new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						GoodsListBean listBean = new GoodsListBean(jsonObject);
						pageNum = Integer.valueOf(listBean.getTotalpage());
						if (mRefreshHeadFlag) {
							adapter = null;
						}
						if (adapter == null) {
							detailInfos = listBean.getGoodsData();
							adapter = new DigouAdapter(detailInfos);
							mListView.setAdapter(adapter);
						} else {
							detailInfos.addAll(listBean.getGoodsData());
							adapter.notifyDataSetChanged();
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	class DigouAdapter extends BaseAdapter {
		private List<GoodsBean> goodsBeans;

		public DigouAdapter(List<GoodsBean> goodsBeans) {
			super();
			this.goodsBeans = goodsBeans;
		}

		@Override
		public int getCount() {
			return goodsBeans.size();
		}

		@Override
		public Object getItem(int position) {
			return goodsBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.adapter_digou_user_item, null);
				holder.mImg_logo = (ImageView) convertView
						.findViewById(R.id.img_logo);
				holder.mTxt_name = (TextView) convertView
						.findViewById(R.id.txt_name);
				holder.mTxt_price = (TextView) convertView
						.findViewById(R.id.txt_price);
				holder.mTxt_num = (TextView) convertView
						.findViewById(R.id.txt_digou_num);
				holder.mTxt_address = (TextView) convertView
						.findViewById(R.id.txt_digou_address);
				holder.mLay_linear_goods = (LinearLayout) convertView
						.findViewById(R.id.lay_linear_goods);
				holder.mTxt_state = (TextView) convertView
						.findViewById(R.id.txt_digou_state);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final GoodsBean goodsBean = goodsBeans.get(position);
			holder.mTxt_name.setText(goodsBean.getGoods_title());
			holder.mTxt_price.setText("￥" + goodsBean.getGoods_price());
			holder.mTxt_num.setText(goodsBean.getGood_num());
			holder.mTxt_address.setText(goodsBean.getGoods_address());

			if (!goodsBean.getImg_url().equals("")) {
				if (goodsBean.getImg_url().contains(",")) {
					imageLoader.displayImage(
							URLCon.HOST
									+ (goodsBean.getImg_url().split(","))[0],
							holder.mImg_logo, options);
				} else {
					imageLoader.displayImage(
							URLCon.HOST + goodsBean.getImg_url(),
							holder.mImg_logo, options);
				}
			} else {
				holder.mImg_logo
						.setImageResource(R.drawable.android_layout_detail);
			}
			if (goodsBean.getState().equals("1")) {
				holder.mTxt_state.setText("已抵购");
			} else {
				holder.mTxt_state.setText("未抵购");
			}
			holder.mLay_linear_goods.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (goodsBean.getState().equals("2")) {
						// 未抵购
						Intent intent = new Intent(context,
								ProductDateilsActivity.class);
						intent.putExtra("goodid", goodsBean.getId());
						intent.putExtra("flag", 1);
						startActivity(intent);

					}
				}
			});
			holder.mLay_linear_goods
					.setOnLongClickListener(new OnLongClickListener() {
						@Override
						public boolean onLongClick(View v) {
							DialogUtils dialogUtils = DialogUtils.getInstance();
							dialogUtils.backDialog(context, "确定删除此抵购商品吗？",
									true, new ReshActivity() {
										@Override
										public void reshActivity() {
											deleteDigou(goodsBean.getRecordid());
										}
									});

							return false;
						}
					});
			return convertView;
		}
	}

	class ViewHolder {
		ImageView mImg_logo;
		TextView mTxt_name;
		TextView mTxt_num;
		TextView mTxt_address;
		TextView mTxt_price;
		TextView mTxt_state;
		LinearLayout mLay_linear_goods;

		RelativeLayout mLay_rela_shop_name;
		ListView mList_goods;
		TextView mTxt_shop_name;
	}

	// 个人删除抵购记录
	private void deleteDigou(String recordId) {
		String path = URLCon.兑换抵购 + "?action=delgoodschangerecord&userid="
				+ userId + "&id=" + recordId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在删除......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
							mRefreshFlag = false;// 判断是否刷新
							indexPage = 1;
							initData(indexPage);
						} else {
							ToastUtil.ShowToast(context,
									jsonObject.optString("msg"));
						}

					}
				});
		asyncTaskUtil.execute(path);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = false;
				mRefreshFlag = true;

				++indexPage;
				if (indexPage > pageNum) {
					ToastUtil.ShowToast(context, "没有更多数据！");
					mPullToRefreshView.onFooterRefreshComplete();
					return;
				} else {
					initData(indexPage);
				}

				// mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1);

	}

	int indexPage = 1;

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = true;
				mRefreshFlag = true;
				// if (async != null) {
				// Utils.cancelTaskInterrupt(async);
				// async = null;
				// }
				indexPage = 1;// 刷新头部时将页数初始化为1
				initData(indexPage);
				// mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1);
	}
}
